<?php

namespace app\admin\controller\school;

use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;

/**
 * 专业管理
 *
 * @icon fa fa-circle-o
 */
class Major extends Backend
{

    /**
     * Major模型对象
     * @var \app\admin\model\school\Major
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\school\Major;
        $this->view->assign("majorLevelDictList", $this->model->getMajorLevelDictList());
        $this->assignconfig("majorLevelDictList", $this->model->getMajorLevelDictList());
        $this->view->assign("workStationDictList", $this->model->getWorkStationDictList());
        $this->assignconfig("workStationDictList", $this->model->getWorkStationDictList());
        $this->view->assign("statusList", $this->model->getStatusList());

        $this->stu = new \app\admin\model\school\Student();
        $this->MVL = new \app\admin\model\school\MajorLesson();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function attendance()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

//            $this->model->with("major");
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
//        $this->assign("config.jsname", "")
        return $this->view->fetch();
    }
    /**
     * 搜索下拉列表
     */
    public function searchlist()
    {
        $result = $this->model->select();
        $searchlist = [];
        foreach ($result as $key => $value) {
            $searchlist[] = ['id' => $value['id'], 'name' => $value['name']];
        }
        $data = ['searchlist' => $searchlist];
        $this->success('', null, $data);
    }

    /**
     * 导出面授记分册-考勤表
     */
    // 2018级编辑出版26专升本
    public function export($ids = "")
    {
        $this->loadlang("school.student");//加载学员信息的语言包，用于获取学院表里的字典信息 

        $ids = explode(',', $ids);//只有一个专业id
        //1、根据专业信息id，获学员信息。
        //获取学员信息
        $studentList = $this->stu->getStudentByMajorId($ids[0]);
        $allStudent = []; //保存所有学院的数组
        for ($j = 0; $j < count($studentList); $j++) {
            $name = $studentList[$j]['name'];
            $sex = $studentList[$j]['student_sex_text'];
            $temp = [
                $j => [$name, $sex]
            ];
            $allStudent += $temp; //添加数组
        }

        $allStudent;//二维数组


        //2、获取课程id，去查询学这个专业的课程信息、
        $major = $this->model->getMajor($ids[0]); //专业详情
        $level = $major['level']; //专业所属的年级
        $lesson = $this->model->getLessonList($cv = null, $major); //专业下所有课程信息。多个
        $num = 0;
        $ll = "";
        $spreadsheet = new Spreadsheet(); //创建一个Excel对象
        $sheet = $spreadsheet->getActiveSheet();
        foreach ($lesson as $les) {
            $info = $this->MVL->getMvL($major["id"], $les["id"]);//数学没有信息 ，7,9
            if(count($info)== 0) continue;
            $arr = $info[0];
            $teacher = $info[0]['admin_ids_text']; //任课老师
            $major_level = $info[0]['major_level_dict_text']; //培养层次
            $ll .= $teacher .'    '. $major_level.';';
            //创建sheet
           
            $sheet = $spreadsheet->createSheet($num)->setTitle($les['name']);
             //获取一个可以操作的sheet页
            //外围边框
            $sheet->getStyle('A4:J28')->applyFromArray([
                'borders' => [ //设置边框
                    'outline' => [
                        'borderStyle' => Border::BORDER_DOUBLE,
                        'color' => ['argb' => '000000']
                    ],
                ],

            ]);
            //设置sheet的名字  两种方法
            
            $this->sheetStyle($sheet);
            $exportData = [
                'A1:J1' => [['1', ''], '北京工作站 2010—2011学年第二学期'],//还得在改
                'A2:J2' => [['2', ''], '面授记分册'],
                'A3:J3' => [['3', ''], '课程名称：《'.$les['name'].'》  班级：'.$level.'   专业：'.$major['name'].'   层次：'.$major_level.'    任课教师：'.$teacher],
                'A4' => [['4', ''], '序号'],
                'B4' => [['4', ''], '姓名'],
                'C4' => [['4', ''], '性别'],
                'D4' => [['4', ''], '一'],
                'E4' => [['4', ''], '二'],
                'F4' => [['4', ''], '三'],
                'G4' => [['4', ''], '四'],
                'H4' => [['4', ''], '五'],
                'I4' => [['4', ''], '六'],
                'J4' => [['4', ''], '平均成绩'],
                'A29:J29' => [['5', ''], '1.每次面授任课教师准确统计学生考勤。出勤：√  迟到早退：×  缺勤：O'],
                'A30:J30' => [['5', ''], '2.期末将统计表上交函授教务科。'],
                'A31:J31' => [['5', ''], '3.学生缺课超过面授课时三分之一，不准参加期末考试。']
            ];

            $i = 1;
            $n = 1;
            //每学期的标题
            for ($j = 5; $j <= 28; $j++) {
                if($n<=count($allStudent)){//当有学员 信息的时候，就录入学员信息
                    $name = $allStudent[$n-1][0];
                    $sex = $allStudent[$n-1][1];
                    $list = [
                        'A' . $j => [['6', ''], $i],
                        'B' . $j => [['6', ''], $name],//姓名
                        'C' . $j => [['6', ''], $sex],//性别
                        'D' . $j => [['6', ''], ''],
                        'E' . $j => [['6', ''], ''],
                        'F' . $j => [['6', ''], ''],
                        'G' . $j => [['6', ''], ''],
                        'H' . $j => [['6', ''], ''],
                        'I' . $j => [['6', ''], ''],
                        'J' . $j => [['6', ''], '']
    
                    ];
                    $n++;
                }else{//当没有学员信息的时候，直接填写空的
                    $list = [
                        'A' . $j => [['6', ''], $i],
                        'B' . $j => [['6', ''], ''],//姓名
                        'C' . $j => [['6', ''], ''],//性别
                        'D' . $j => [['6', ''], ''],
                        'E' . $j => [['6', ''], ''],
                        'F' . $j => [['6', ''], ''],
                        'G' . $j => [['6', ''], ''],
                        'H' . $j => [['6', ''], ''],
                        'I' . $j => [['6', ''], ''],
                        'J' . $j => [['6', ''], '']
    
                    ];
                }
                $exportData += $list; //添加数组
                $i++;
            }

            $this->exportStyle2($exportData, $sheet);
            //一个课程对应一个sheet
            //有相同的学生
            $num++;
        }



        //第二种直接页面上显示下载
        $file_name = '面授积分表' . ".xls";
        //        header('Content-Type: application/vnd.ms-excel');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $file_name . '"');
        header('Cache-Control: max-age=0');
        $writer = IOFactory::createWriter($spreadsheet, 'Xls');
        //注意createWriter($spreadsheet, 'Xls') 第二个参数首字母必须大写
        $writer->save('php://output');
        exit;
    }
    function sheetStyle($sheet)
    {
        $sheet->getColumnDimension('J')->setWidth(30);
    }
    function exportStyle2($exportData = [], $sheet)
    {
        $sheet->getColumnDimension('B')->setWidth(11);
        //正文加粗字体
        $font1 =  [
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER, //水平居中
                'vertical' => Alignment::VERTICAL_CENTER, //上下居中
            ],
            'font' => [
                'name' => '仿宋_GB2312',
                'bold' => true,
                'size' => 20,
            ]
        ];
        //正文普通字体
        $font2 =  [
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER, //水平居中
                'vertical' => Alignment::VERTICAL_CENTER, //上下居中
            ],
            'font' => [
                'name' => '仿宋_GB2312',
                'bold' => true,
                'size' => 18,
            ]
        ];

        //正文普通小字体
        $font3 =  [
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER, //水平居中
                'vertical' => Alignment::VERTICAL_CENTER, //上下居中
            ],
            'font' => [
                'name' => '仿宋_GB2312',
                'size' => 12,
            ]
        ];

        //列名
        $font4 =  [
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER, //水平居中
                'vertical' => Alignment::VERTICAL_CENTER, //上下居中
            ],
            'font' => [
                'name' => '仿宋_GB2312',
                'size' => 16,
                'bold' => true,
            ],
            'borders' => [ //设置边框
                'outline' => [
                    'borderStyle' => Border::BORDER_THIN,
                    'color' => ['argb' => '000000']
                ],
            ]
        ];
        //底下文字
        $font5 =  [
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_LEFT, //水平居左
                'vertical' => Alignment::VERTICAL_CENTER, //上下居中
            ],
            'font' => [
                'name' => '仿宋_GB2312',
                'size' => 14,
            ]
        ];
        //正文
        $font6 =  [
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_CENTER, //水平居中
                'vertical' => Alignment::VERTICAL_CENTER, //上下居中
            ],
            'font' => [
                'name' => '仿宋_GB2312',

                'size' => 13,
            ],
            'borders' => [ //设置边框
                'outline' => [
                    'borderStyle' => Border::BORDER_THIN,
                    'color' => ['argb' => '000000']
                ],
            ]
        ];
        $font7 =  [
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_LEFT, //水平居左
                'vertical' => Alignment::VERTICAL_CENTER, //上下居中
            ],
            'font' => [
                'name' => '仿宋_GB2312',
                'bold' => true,
                'size' => 9,
            ],
            'borders' => [ //设置边框
                'outline' => [
                    'borderStyle' => Border::BORDER_THIN,
                    'color' => ['argb' => '000000']
                ],
            ]
        ];
        foreach ($exportData as $key => $value) {
            $arr = explode(':', $key);
            if (count($arr) == 2) { //融合多單元格
                $sheet->mergeCells($key); //跟据key融合
                $sheet->setCellValue($arr[0], $value[1]); //設置值
            } else { //单个单元格

                $sheet->setCellValue($key, $value[1]); //設置值
            }

            switch ($value[0][0]) { //設置樣式
                case '1':
                    $sheet->getStyle($key)->applyFromArray($font1);
                    break;
                case '2':
                    $sheet->getStyle($key)->applyFromArray($font2);
                    break;
                case '3':
                    $sheet->getStyle($key)->applyFromArray($font3);
                    break;
                case '4':
                    $sheet->getStyle($key)->applyFromArray($font4);
                    break;
                case '5':
                    $sheet->getStyle($key)->applyFromArray($font5);
                    break;
                case '6':
                    $sheet->getStyle($key)->applyFromArray($font6);
                    break;
                case '7':
                    $sheet->getStyle($key)->applyFromArray($font7);
                    break;
                default:
                    $sheet->getStyle($key)->applyFromArray($font2);
                    break;
            }
            if ($value[0][1] == 'warpText') {
                $sheet->getStyle($key)->getAlignment()->setWrapText(true); //自动换行
            }
        }
    }
}
